import { Button, message } from 'antd'
import { Modal } from '@/desktop/components'
import { ChooseAccountInput } from '@/desktop/components/ChooseAccount'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { BaseAccount } from '@/services/auth'
import type { AccountQywx, FullSearchContact } from './logic'
import './AnyTransfer.module.less'

export default function AnyTransfer(props: {
  item: { contact: FullSearchContact; qywx: AccountQywx } | null
  onFinish: (confirmed: boolean) => void
}) {
  const { item, onFinish } = props
  return <Modal
    open={!!item}
    styleName="modal"
    title="建立聊天"
    footer={null}
    width="450px"
    onCancel={() => onFinish(false)}
  >
    {item ? <Content item={item} onFinish={onFinish} /> : null}
  </Modal>
}

function Content(props: {
  item: { contact: FullSearchContact; qywx: AccountQywx }
  onFinish: (confirmed: boolean) => void
}) {
  const {
    item: { contact, qywx },
    onFinish,
  } = props
  const [account] = useStreams(services.auth.account$)
  const [target, setTarget] = useState<BaseAccount | null>(null)
  const [submitting, setSubmtting] = useState(false)

  const makeTransfer = async () => {
    if (!target) return

    setSubmtting(true)
    const fromAccount = { id: qywx.accountId, name: qywx.accountName } // 客户可能不是当前账号的，所以要从企业微信中获取信息
    const remark = `任意客户转交（由 ${account?.name ?? ''} 发起）`
    const res = await services.transfers.transfer({
      contact,
      qywx,
      fromAccount,
      targetAccount: target,
      remark,
    })
    setSubmtting(false)

    if (res.success) {
      void services.transfers.load()
      void message.success('聊天发起成功')
      onFinish(true)
    } else {
      void message.warning(`聊天发起失败：${res.error}`)
    }
  }

  return <div styleName="wrap">
    <div styleName="content">
      <header>指定此客户的聊天对象：</header>
      <ChooseAccountInput
        value={target?.id}
        disabled={[qywx.accountId]}
        onChange={(id, target) => setTarget(target)}
      />
    </div>
    <footer>
      <Button onClick={() => onFinish(false)}>取消</Button>
      <Button type="primary" onClick={makeTransfer} loading={submitting} disabled={!target}>
        确定
      </Button>
    </footer>
  </div>
}
